import React from 'react';
import {
  View,
  ScrollView,
  TouchableOpacity,
  Platform,
  Alert,
} from 'react-native';
import {Text, Button, ListItem} from '@rneui/base';
import {
  useDebounceEffect,
  useMap,
  useMount,
  useSafeState,
  useSetState,
  useUpdateEffect,
} from 'ahooks';
import {round} from 'lodash';
import style from './style.less';
import {
  requestMultiple,
  checkMultiple,
  PERMISSIONS,
  RESULTS,
  openSettings,
  request,
} from 'react-native-permissions';
import {useNavigation} from '@react-navigation/native';
import {MapPowerResult, MapPowerName} from '@/config/power';
import {CkPowerWaitMs} from '@/config/common';
import dayjs from 'dayjs';
import {useSelector, useDispatch} from 'react-redux';
import Modal from 'react-native-modal';
import {
  useSafeAreaFrame,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';

export default ({children, clickPowers = [], ...otherProps}) => {
  const frame = useSafeAreaFrame();
  const navigation = useNavigation();
  const appRunState = useSelector(state => state.appRunState.value);

  const [allowPowers, setAllowPowers] = useSafeState([]);
  const [group, setGropu] = useSafeState([]);
  const [unavailablePowers, setUnavailablePowers] = useSafeState([]);
  const [isModalVisible, setModalVisible] = useSafeState(true);

  const setInfo = async () => {
    const newMap = new Map();
    for (const name of new Set(clickPowers)) {
      const key = PERMISSIONS.ANDROID[name] || name;
      newMap.set(key, {name: name});
    }
    const powerList = [...newMap].map(([key]) => key);
    try {
      const statuses = await checkMultiple(powerList);
      for (const [key, powerStr] of Object.entries(statuses)) {
        const oldData = newMap.get(key);
        newMap.set(key, {...oldData, powerStr});
      }

      const getPowersArr = targetValue => {
        const items = [];
        [...newMap].forEach(([, item]) => {
          if (item.powerStr === targetValue) {
            items.push(item);
          }
        });
        return items;
      };

      const allows = getPowersArr(RESULTS.GRANTED);
      setAllowPowers(allows);

      const unavailables = getPowersArr(RESULTS.UNAVAILABLE);
      setUnavailablePowers(unavailables);

      const gArr = [
        // RESULTS.GRANTED,
        RESULTS.LIMITED,
        RESULTS.DENIED,
        RESULTS.BLOCKED,
        // RESULTS.UNAVAILABLE,
      ];
      const rtArr = [];
      gArr.forEach(targetValue => {
        rtArr.push(getPowersArr(targetValue));
      });
      setGropu(rtArr);
    } catch (e) {
      console.log('获取权限异常', e.message);
    }
  };

  useMount(() => {
    setInfo();
  });
  useDebounceEffect(
    () => {
      setInfo();
    },
    [appRunState],
    {wait: 0},
  );

  const onPress = async () => {
    if (unavailablePowers.length) {
      let names = unavailablePowers.map(
        item => MapPowerName.get(item.name) || item.name,
      );
      let str = names.join('；');
      Alert.alert(`本机不支持权限：${str}`);
      return;
    }

    const refules = [];
    group.forEach(gRows => {
      gRows.forEach(item => {
        if (item) {
          refules.push(item);
        }
      });
    });
    // console.log('refules', refules, 'group', group, 'clickPowers', clickPowers);
    console.log('refules', refules);
    setModalVisible(true);
  };
  const ModalBox = () => (
    <Modal
      isVisible={isModalVisible}
      onBackdropPress={() => setModalVisible(false)}>
      <View style={{backgroundColor: '#fff', maxHeight: Math.round(frame.height)/ 2}}>
        <ScrollView style={{flex: 0}}>
          {new Array(50).fill().map((item, index) => (
            <Text key={index}>Index{index}</Text>
          ))}
          <Button
            title="Hide modal"
            onPress={() => {
              setModalVisible(!isModalVisible);
            }}
          />
        </ScrollView>
      </View>
    </Modal>
  );
  const ChildrenCom = () => {
    return React.cloneElement(children, {
      ...otherProps,
      onPress: onPress,
    });
  };

  if (allowPowers.length !== clickPowers.length) {
    return (
      <>
        <ChildrenCom />
        <ModalBox />
      </>
    );
  }

  return React.cloneElement(children, {...otherProps});
};
